<?php
/*************************************************************************************
   Copyright notice

   This script uses some code parts of the glossary module for phpwcms (c) Oliver Georgi
   (c) 2002-2009 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.

   This script uses some code parts from bmcatalog module
   (c) 2010 Benjamin Matzmorr, www.etype.de

   (c) 2012 webrealisierung gmbh, www.webrealisierung.ch
   Catalogue Module V 1.0.0  -  Date: 2012-06-01

   The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
   A copy is found in the textfile GPL.txt and important notices to the license
   from the author is found in LICENSE.txt distributed with these scripts.

   This script is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.  See the GNU General Public License for more details.

   This copyright notice MUST APPEAR in all copies of the script!
*************************************************************************************/
// ----------------------------------------------------------------
// obligate check for phpwcms constants
if (!defined('PHPWCMS_ROOT')) {
   die("You Cannot Access This Script Directly, Have a Nice Day.");
}
// ----------------------------------------------------------------

// check if form should be closed only -> and back to listing mode
if( isset($_POST['close']) ) {
	headerRedirect( ctg_map_url('controller=entry', '') );
}

//include google maps code
include(MODULE_CTG_PATH.'inc/googlemapsapi.php');

// try
if(isset($_GET['edit'])) {
	$plugin['edit_id']		= intval($_GET['edit']);
} else {
	$plugin['edit_id']		= 0;
}

// process post form
if(isset($_POST['ctg_title']) &&  $action == 'edit') {

	//file
	$plugin['tmp_file'] = array();

	if (intval($_POST['ctg_file_id'])>0) {

		$plugin['file_sql'] = "SELECT * FROM " . DB_PREPEND . "phpwcms_file WHERE f_id=" . intval($_POST['ctg_file_id']) . " LIMIT 1;";
  	$plugin['file_data'] = _dbQuery($plugin['file_sql'], 'SELECT');

			if (isset($plugin['file_data'][0])) {
				//file contents
				$plugin['tmp_file'][0]  = intval($_POST['ctg_file_id']);
				$plugin['tmp_file'][1] = $plugin['file_data'][0]['f_name'];
				$plugin['tmp_file'][2] = $plugin['file_data'][0]['f_hash'];
				$plugin['tmp_file'][3] = $plugin['file_data'][0]['f_ext'];
				$plugin['tmp_file'][4]= 0;
				$plugin['tmp_file'][5] = 0;
				$plugin['tmp_file'][6] = clean_slweg($_POST['ctg_file_caption']);
				$plugin['tmp_file'][7] = 0;
				$plugin['tmp_file'][8] = 0;
			}
	}

  //image
  $plugin['tmp_gallery'] = array();
  $plugin['gallery'] = ( isset($_POST['ctg_gallery']) ) ?  intval($_POST['ctg_gallery']) : 0 ;


    $plugin['tmp_gallery1'] = array();
    $plugin['tmp_gallery1']['root'] = empty($_POST['ctg_gallery1_root'])  ? '' : clean_slweg($_POST['ctg_gallery1_root']);
//    $plugin['tmp_gallery1']['width'] = empty($_POST['ctg_image1_width'])  ? '' : intval($_POST['ctg_image1_width']);
//    $plugin['tmp_gallery1']['height'] = empty($_POST['ctg_image1_height'])  ? '' : intval($_POST['ctg_image1_height']);
//    $plugin['tmp_gallery1']['crop'] = empty($_POST['ctg_image1_crop'])  ? 0 : intval($_POST['ctg_image1_crop']);
//    $plugin['tmp_gallery1']['zoom'] = empty($_POST['ctg_image1_zoom'])  ? 0 : intval($_POST['ctg_image1_zoom']);
//    $plugin['tmp_gallery1']['pag'] = empty($_POST['ctg_image1_pag'])  ? 0 : intval($_POST['ctg_image1_pag']);
//    $plugin['tmp_gallery1']['pagnr'] = empty($_POST['ctg_image1_pagnr'])  ? '' : intval($_POST['ctg_image1_pagnr']);

    $plugin['tmp_gallery0'] = array();
    $plugin['tmp_gallery0']['data'] = array();
    $plugin['tmp_gallery0']['image_data'] = array();
  	//get image ids ( post values )
  	$plugin['tmp_gallery0']['ctge_images']	= (isset($_POST['ctg_images']) && is_array($_POST['ctg_images'])) ? $_POST['ctg_images'] : array();

  	//get image captions
  	$plugin['tmp_gallery0']['ctge_caption'] = clean_slweg($_POST["ctg_caption"], 0 , false);
  	$plugin['tmp_gallery0']['ctge_caption'] = explode(LF, $plugin['tmp_gallery0']['ctge_caption']);

  	//someting to do ? ok lets get things done
  	if(is_array($plugin['tmp_gallery0']['ctge_images']) && count($plugin['tmp_gallery0']['ctge_images'])) {

  		$plugin['tmp_gallery0']['ctge_images'] = array_map('intval', $plugin['tmp_gallery0']['ctge_images']);
  		$plugin['tmp_gallery0']['ctge_images'] = array_diff($plugin['tmp_gallery0']['ctge_images'], array(0,'',NULL,false));

  		if(count($plugin['tmp_gallery0']['ctge_images'])) {

        $plugin['image_sql'] = 'SELECT f_id, f_aktiv, f_name, f_size, f_ext, f_hash FROM '.DB_PREPEND.'phpwcms_file WHERE f_id IN ('.implode(',', $plugin['tmp_gallery0']['ctge_images']).')';
        $plugin['image_sqldata'] = _dbQuery($plugin['image_sql'], 'SELECT');

  			//take all values from db
  			foreach($plugin['image_sqldata'] as $value) {
  				$plugin['tmp_gallery0']['image_data'][ $value['f_id'] ] = $value;
  			}

  			// now run though image result - but keep sorting
  			foreach($plugin['tmp_gallery0']['ctge_images'] as $key => $value) {
  				if ( isset($plugin['tmp_gallery0']['image_data'][$value]) ) {

  					$plugin['tmp_gallery0']['data'][$key]		= $plugin['tmp_gallery0']['image_data'][$value];
  					$plugin['tmp_gallery0']['data'][$key]['zoom']		= empty($_POST['bmc_image0_zoom']) ? 0 : 1;	//zoom ?
  					$plugin['tmp_gallery0']['data'][$key]['caption']	= isset($plugin['tmp_gallery0']['ctge_caption'][$key]) ? trim($plugin['tmp_gallery0']['ctge_caption'][$key]) : '';

  				}
  			}
  		}
  	}
//    $plugin['tmp_gallery0']['width'] = empty($_POST['ctg_image0_width'])  ? '' : intval($_POST['ctg_image0_width']) ;
//    $plugin['tmp_gallery0']['height'] = empty($_POST['ctg_image0_height'])  ? '' : intval($_POST['ctg_image0_height']) ;
//    $plugin['tmp_gallery0']['crop'] = empty($_POST['ctg_image0_crop'])  ? 0 : intval($_POST['ctg_image0_crop']) ;
//    $plugin['tmp_gallery0']['zoom'] = empty($_POST['ctg_image0_zoom'])  ?  0 : intval($_POST['ctg_image0_zoom']) ;

  if ($plugin['gallery'] == 1) { //folder images
    $plugin['tmp_gallery0']['active'] = 0;
    $plugin['tmp_gallery1']['active'] = 1;
  } else { //phpwcms images
    $plugin['tmp_gallery0']['active'] = 1;
    $plugin['tmp_gallery1']['active'] = 0;
  }

  $plugin['tmp_gallery'][0] = $plugin['tmp_gallery0'];
  $plugin['tmp_gallery'][1] = $plugin['tmp_gallery1'];


  //address
	$plugin['tmp_address'] = array();
	$plugin['tmp_address']['address']		=  empty($_POST["ctg_address"]) ? '' : clean_slweg($_POST["ctg_address"]);
	$plugin['tmp_address']['zip']			=  empty($_POST["ctg_zip"]) ? '' : clean_slweg($_POST["ctg_zip"]);
	$plugin['tmp_address']['city']			=  empty($_POST["ctg_city"]) ? '' : clean_slweg($_POST["ctg_city"]);
	$plugin['tmp_address']['country']		=  empty($_POST["ctg_country"]) ? '' : clean_slweg($_POST["ctg_country"]);
	$plugin['tmp_address']['show_map']		= empty($_POST['ctg_show_map']) ? 0 : 1;
	$plugin['tmp_address']['long']			= empty($_POST["ctg_lng"]) ? 0 : clean_slweg($_POST["ctg_lng"]);
	$plugin['tmp_address']['lat']			= empty($_POST["ctg_lat"]) ? 0 : clean_slweg($_POST["ctg_lat"]);
	$plugin['tmp_address']['marker']   		= empty($_POST["ctg_marker"]) ? '' : clean_slweg($_POST["ctg_marker"]);

  //tags
	$plugin['tmp_tags'] = explode(",", clean_slweg(trim($_POST["ctg_tags"],", ") ) );

	// array to save into db
	$plugin['data'] = array(

				'ctge_id'				=> intval($_POST['ctg_id']),
				'ctge_title'			=> clean_slweg($_POST['ctg_title']),
				'ctge_title2'			=> empty($_POST['ctg_title2']) ? '' : clean_slweg($_POST['ctg_title2']),
        'ctge_catalogid' => empty($_POST['ctg_catalogid']) ?  "" : "|". implode('|', array_map('intval', $_POST['ctg_catalogid'])) ."|",
				'ctge_tags'		=>  empty($_POST['ctg_tags']) ?  "" : "|". implode('|', array_map('trim', $plugin['tmp_tags'])) ."|",
				'ctge_created'			=> date('Y-m-d H:i:s'),
				'ctge_changed'			=> date('Y-m-d H:i:s'),
				'ctge_text'			=> empty($_POST['ctg_text']) ? '' : slweg($_POST['ctg_text']),
				'ctge_text2'			=> empty($_POST['ctg_text2']) ? '' : slweg($_POST['ctg_text2']),
				'ctge_status'			=> empty($_POST['ctg_status']) ? 0 : 1,
				'ctg_img_object'		=> serialize($plugin['tmp_gallery']),
				'ctge_file_object'		=> serialize($plugin['tmp_file']),
	//			'ctg_address_object'	=> serialize($plugin['tmp_address']),
        'ctge_userId' => intval($_POST['ctge_userId']), //int(11) NOT NULL default '0'
				'ctge_address_address'			=> $plugin['tmp_address']['address'],
				'ctge_address_city'			=> $plugin['tmp_address']['city'],
				'ctge_address_zip'			=> $plugin['tmp_address']['zip'],
				'ctge_address_country'			=> $plugin['tmp_address']['country'],
				'ctge_address_long'			=> $plugin['tmp_address']['long'],
				'ctge_address_lat'			=> $plugin['tmp_address']['lat'],
				'ctge_address_marker'			=> $plugin['tmp_address']['marker'],
				'ctge_address_show_map'			=> $plugin['tmp_address']['show_map']
				);



// required fields
	if(empty($plugin['data']['ctge_title'])) {
		$plugin['error']['ctge_title'] = 1;
    $plugin['data']['ctge_catalogid'] =  empty($_POST['ctg_catalogid']) ? array() : array_map('intval', $_POST['ctg_catalogid']);
    $plugin['data']['file']	= array(0=>intval($_POST['ctg_file_id']),1=>clean_slweg($_POST['ctg_file_name']),6=>clean_slweg($_POST['ctg_file_caption']));
    $plugin['data']['images']	= $plugin['tmp_gallery'][0]['data'];
    $plugin['data']['ctge_images'][0] =  $plugin['tmp_gallery'][0];
    $plugin['data']['ctge_images'][1] =  $plugin['tmp_gallery'][1];
	}

	//clean up
	unset($plugin['tmp_gallery']);
  unset($plugin['tmp_gallery0']);
  unset($plugin['tmp_gallery1']);
	unset($plugin['tmp_file']);
	unset($plugin['tmp_address']);
	unset($plugin['tmp_tags']);


	// error ... from what !? maybe this line of code is not needed ... saving should be done anyway
	if(!isset($plugin['error'])) {

		//update oder new one ?
		if($plugin['data']['ctge_id']) {

			// UPDATE
			$sql  = 'UPDATE '.DB_PREPEND.'phpwcms_mod_catalogue_entry SET ';
			$sql .= "ctge_catalogid='".aporeplace($plugin['data']['ctge_catalogid'])."', ";
			$sql .= "ctge_title='".aporeplace($plugin['data']['ctge_title'])."', ";
			$sql .= "ctge_title2='".aporeplace($plugin['data']['ctge_title2'])."', ";
			$sql .= "ctge_tags='".aporeplace($plugin['data']['ctge_tags'])."', ";
			$sql .= "ctge_text='".aporeplace($plugin['data']['ctge_text'])."', ";
			$sql .= "ctge_text2='".aporeplace($plugin['data']['ctge_text2'])."', ";
			$sql .= "ctge_changed='".aporeplace($plugin['data']['ctge_changed'])."', ";
			$sql .= "ctge_status='".aporeplace($plugin['data']['ctge_status'])."', ";
			$sql .= "ctge_image='".aporeplace( $plugin['data']['ctg_img_object'])."', ";
			$sql .= "ctge_file='".aporeplace($plugin['data']['ctge_file_object'])."', ";
	//		$sql .= "ctge_address='".aporeplace($plugin['data']['ctg_address_object'])."', ";
			$sql .= "ctge_userId='".aporeplace($plugin['data']['ctge_userId'])."', ";
			$sql .= "ctge_address_address='".aporeplace($plugin['data']['ctge_address_address'])."', ";
			$sql .= "ctge_address_city='".aporeplace($plugin['data']['ctge_address_city'])."', ";
			$sql .= "ctge_address_zip='".aporeplace($plugin['data']['ctge_address_zip'])."', ";
			$sql .= "ctge_address_country='".aporeplace($plugin['data']['ctge_address_country'])."', ";
			$sql .= "ctge_address_long='".aporeplace($plugin['data']['ctge_address_long'])."', ";
			$sql .= "ctge_address_lat='".aporeplace($plugin['data']['ctge_address_lat'])."', ";
			$sql .= "ctge_address_marker='".aporeplace($plugin['data']['ctge_address_marker'])."', ";
			$sql .= "ctge_address_show_map='".aporeplace($plugin['data']['ctge_address_show_map'])."' ";

			$sql .= " WHERE ctge_id=".$plugin['data']['ctge_id'];

      _dbQuery($sql, 'UPDATE')or die("error: file ".__FILE__." line ".__LINE__.mysql_error() . "<hr />" . $sql);

		} else {

			// INSERT
			$sql  = 'INSERT INTO '.DB_PREPEND.'phpwcms_mod_catalogue_entry (';
			$sql .= 'ctge_catalogid, ctge_created, ctge_changed, ctge_title, ctge_title2,  ';
			$sql .= 'ctge_text,ctge_text2, ctge_tags,ctge_status,ctge_image,ctge_file,ctge_address_address,ctge_address_city,ctge_address_zip,ctge_address_country,ctge_address_long,ctge_address_lat,ctge_address_marker,ctge_address_show_map,ctge_userId';
			$sql .= ') VALUES (';
			$sql .= "'".aporeplace($plugin['data']['ctge_catalogid'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_created'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_changed'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_title'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_title2'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_text'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_text2'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_tags'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_status'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctg_img_object'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_file_object'])."', ";
	//		$sql .= "'".aporeplace($plugin['data']['ctg_address_object'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_address'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_city'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_zip'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_country'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_long'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_lat'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_marker'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_address_show_map'])."', ";
			$sql .= "'".aporeplace($plugin['data']['ctge_userId'])."' ";
			$sql .= ')';

  		$result = _dbQuery($sql, 'INSERT');

			if( !empty($result['INSERT_ID']) ) {
				$plugin['data']['ctge_id']	= $result['INSERT_ID'];
			}
		}

		// save and back to listing mode
		if( isset($_POST['save']) ) {
			headerRedirect( ctg_map_url('controller=entry', '') );
		} else {
			headerRedirect( ctg_map_url( array('controller=entry', 'edit='.$plugin['data']['ctge_id']), '') );
		}

	}	// no error

}	//title is set

// try to read entry from database
if($plugin['edit_id'] && !isset($plugin['error'])) {

	$sql  = 'SELECT * FROM '.DB_PREPEND.'phpwcms_mod_catalogue_entry WHERE ctge_id='.$plugin['edit_id']. ' LIMIT 1';
	$plugin['data'] = _dbQuery($sql);

		if( isset($plugin['data'][0]) ) {
      $plugin['data'] = $plugin['data'][0];
      $plugin['data']['ctge_tags_tmp'] = explode('|',trim($plugin['data']['ctge_tags'], '|'));
      $plugin['data']['ctge_tags_tmp'] = implode( ', ', $plugin['data']['ctge_tags_tmp']);
      $plugin['data']['ctge_tags'] = empty($plugin['data']['ctge_tags_tmp']) ? "" : $plugin['data']['ctge_tags_tmp'].", " ;
      $plugin['data']['ctge_catalogid'] = explode('|',trim($plugin['data']['ctge_catalogid'], '|'));

    	$plugin['data']['tmpimages'] =	@unserialize($plugin['data']['ctge_image']);
      $plugin['data']['ctge_images'][0] = 	$plugin['data']['tmpimages'][0];
      $plugin['data']['ctge_images'][1] = 	$plugin['data']['tmpimages'][1];
      $plugin['data']['images'] = $plugin['data']['tmpimages'][0]['data'];
    	if(!count($plugin['data']['images'])) {
    		$plugin['data']['images']	= array();
    	}

    	$plugin['data']['file']= @unserialize($plugin['data']['ctge_file']);
    	if(!count($plugin['data']['file'])) {
    		$plugin['data']['file']	= array(0=>'',1=>'',6=>'');
    	}
/*
    	$plugin['data']['address']= @unserialize($plugin['data']['ctg_address']);
    	if(!count($plugin['data']['address'])) {
    		$plugin['data']['address']	= array('address'=>'','zip'=>'','city'=>'','country'=>'','long'=>'','lat'=>'','show_map'=>0,'marker'=>'');
    	}
*/

//map image info
// 0   :1       :2   :3        :4    :5     :6      :7       :8
// dbid:filename:hash:extension:width:height:caption:position:zoom
		} else {
			headerRedirect( ctg_map_url('controller=entry', '') );
		}
}

if($action == 'status') {
  $plugin['data'] = array();
	list($plugin['data']['ctge_id'], $plugin['data']['ctge_status']) = explode( '-', $_GET['verify'] );
	$plugin['data']['ctge_id']		= intval($plugin['data']['ctge_id']);
	$plugin['data']['ctge_status']	= empty($plugin['data']['ctge_status']) ? 1 : 0;
}

if($action == 'delete') {
  $plugin['data'] = array();
	$plugin['data']['ctge_entry_del'] = intval($_GET['delete']);
}

// default values
if(empty($plugin['data'])) {

	$plugin['data'] = array(

				'ctge_id'			=> 0,
				'ctge_title'		=> '',
				'ctge_title2'		=> '',
				'ctge_created'		=> '',
				'ctge_changed'		=> date('Y-m-d H:i:s'),
        'ctge_tags' => '',
        'ctge_catalogid' => array(),
				'ctge_text'		=> '',
				'ctge_text2'		=> '',

				'ctge_images'		=> array(
          0 => array(
//    				'width'		=> '',
//    				'height'	=> '',
//    				'crop'		=> 0,
//            'zoom'		=> 0,
            'active'		=> 1
          ),
          1 => array(
            'root'		=> '',
//            'width'		=> '',
//    				'height'	=> '',
//    				'crop'		=> 0,
//            'zoom'		=> 0,
//            'pag'		=> 0,
//            'pagnr'		=> '',
            'active'		=> 0
          )
        ),


        'img_captions' => array(),
				'ctge_status'		=> 1,
				'ctge_file'		=> '',
//				'ctg_address'		=> '',
				'ctge_address_address'		=> '',
				'ctge_address_city'		=> '',
				'ctge_address_zip'		=> '',
				'ctge_address_country'		=> '',
				'ctge_address_long'		=> '',
				'ctge_address_lat'		=> '',
				'ctge_address_marker'		=> '',
				'ctge_address_show_map'		=> 0,
				'ctge_userId'		=> 0,
        'images' => array(),
				'file'			=> array(0=>'',1=>'',6=>'')
//				'address'		=> array('address'=>'','zip'=>'','city'=>'','country'=>'','long'=>'','lat'=>'','show_map'=>0,'marker'=>'')


			);

}
?>